/**
 * Copyright (C) 2008 http://code.google.com/p/maven-license-plugin/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.mojo.license.header;

import com.google.code.xmltool.CallBack;
import com.google.code.xmltool.XMLDocument;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Cedric Pronzato
 */
public class AdditionalHeaderDefinition
{
    private final Map<String, HeaderDefinition> definitions = new HashMap<String, HeaderDefinition>();

    public AdditionalHeaderDefinition(XMLDocument doc)
    {
        doc.gotoRoot().forEachChild(new CallBack()
        {
            public void execute(XMLDocument doc)
            {
                final String type = doc.getCurrentTagName().toLowerCase();
                HeaderDefinition definition = definitions.get(type);
                if (definition == null)
                {
                    definition = new HeaderDefinition(type);
                    definitions.put(type, definition);
                }
                doc.forEachChild(new FeedProperty(definition));
                definition.validate();
            }
        });
    }

    public Map<String, HeaderDefinition> getDefinitions()
    {
        return definitions;
    }

    private static final class FeedProperty implements CallBack
    {
        private final HeaderDefinition definition;

        private FeedProperty(HeaderDefinition definition)
        {
            this.definition = definition;
        }

        public void execute(XMLDocument xmlDocument)
        {
            String value = xmlDocument.getText();
            if ("".equals(value)) // value can't be null
            {
                value = xmlDocument.getCDATA();
            }
            definition.setPropertyFromString(xmlDocument.getCurrentTagName(), value);
        }
    }
}
